#coding:utf-8
import hashlib
import json
import time
import datetime
from lovewith.account.models import MtUser, MtUserAuth, MtuserGetPassword


class UserApi:
    def __init__(self):
        pass

    #校验user数据
    @staticmethod
    def check_data(user_id=None, app_uid=None, account_type=None):
        user_data = None
        if user_id:
            if not app_uid and not account_type:
                user_data = MtUser.objects.filter(id=int(user_id))
        else:
            if app_uid and account_type:
                user_data = MtUser.objects.filter(app_uid=app_uid, account_type=int(account_type))

        if user_data and user_data.exists():
            return user_data[0]
        else:
            return False

    #更新商业信息
    @staticmethod
    def update_biz_data(user, fullname, phone, qq):
        user_filter_data = MtUser.objects.filter(id=user.id)

        if user_filter_data.exists():
            user_data = user_filter_data[0]
            user_data.full_name = fullname
            user_data.phone = phone
            user_data.qq = qq
            user_data.save()

            return 1
        else:
            return -1

    #根据email查找用户信息
    @staticmethod
    def check_user(email=None, username=None):
        if email:
            user_filter_data = MtUser.objects.filter(email=email)
            if user_filter_data.exists():
                return user_filter_data[0]

        if username:
            user_filter_data = MtUser.objects.filter(username=username)
            if user_filter_data.exists():
                return user_filter_data[0]

        return False

    #添加普通用户
    @staticmethod
    def add(password=None, app_uid=None, username=None, email=None, gender=None, avatar=None, account_type=None):
        if password and username and email and account_type:
            return MtUser.objects.create_user(password=password, app_uid=app_uid, username=username, email=email,
                                              gender=gender, avatar=avatar, account_type=account_type)

    #添加授权信息
    @staticmethod
    def update_auth(user, user_type, username, token, expires):
        user_auth_filter_data = MtUserAuth.objects.filter(user_id=user.id, type=user_type)
        if user_auth_filter_data.exists():
            user_auth_data = user_auth_filter_data[0]
            user_auth_data.username = username
            user_auth_data.access_token = token
            user_auth_data.token_expires = expires
            user_auth_data.save()
        else:
            new_user_auth = MtUserAuth(
                user=user,
                type=user_type,
                username=username,
                access_token=token,
                token_expires=expires
            )
            new_user_auth.save()

    #获取第三方网站用户名
    @staticmethod
    def get_auth_username(user_id, user_type):
        user_filter_data = MtUserAuth.objects.filter(user_id=user_id, type=user_type)
        if user_filter_data.exists():
            return user_filter_data[0].username

    #获取授权信息
    @staticmethod
    def get_auth(user_id):
        auth_data = {}
        auth_filter_data = MtUserAuth.objects.filter(user_id=user_id)
        for au in auth_filter_data:
            is_expires = True
            now = time.time()
            au_type = None

            if au.type == 1:
                au_type = 'sina'
            if au.type == 2:
                au_type = 'qq'

            if float(au.token_expires) > float(now):
                is_expires = False

            if au_type:
                auth_data[au_type] = {
                    'username': au.username,
                    'type': au.type,
                    'token': au.access_token,
                    'expires': au.token_expires,
                    'is_expires': is_expires,
                    'sync': json.loads(au.sync_config)
                }

        return auth_data

    #删除授权信息
    @staticmethod
    def delete_auth(user_id, account_type):
        auth_filter_data = MtUserAuth.objects.filter(user_id=user_id, type=account_type)
        auth_filter_data.delete()

    #更新授权信息
    @staticmethod
    def update_sync(user_id, account_type, sync_data):
        auth_filter_data = MtUserAuth.objects.filter(user_id=user_id, type=account_type)
        if auth_filter_data.exists():
            auth_data = auth_filter_data[0]
            auth_data.sync_config = sync_data
            auth_data.save()


    #校验找回密码key是否合法
    @staticmethod
    def validate_getpwd_key(key):
        confirm_key_data = MtuserGetPassword.objects.filter(confirm_key=key)
        if confirm_key_data.exists():
            confirm_data = confirm_key_data[0]
            if not confirm_data.used:
                expires_date = confirm_data.expires_date
                now_time = datetime.datetime.now()
                if now_time <= expires_date:
                    #未被使用也未过期
                    return confirm_data

        return None


    #增加找回密码记录
    @staticmethod
    def add_getpassword_log(user):
        confirm_key = hashlib.new('md5', '%s-%s-%s-%s' % (user.username, user.email, user.password, time.time()))
        confirm_key = confirm_key.hexdigest()
        expires_date = datetime.datetime.now() + datetime.timedelta(days=1)

        new_getpwd = MtuserGetPassword(
            confirm_key=confirm_key,
            expires_date=expires_date,
            user=user
        )
        new_getpwd.save()

        return confirm_key













